// 新增导入
import { useEffect, useState } from 'react';
import axios from 'axios';
import { motion } from 'framer-motion';
import { useUserStore } from '../../store/userStore';
import { Task } from '../../types';

export const PersonalChallenges: React.FC = () => {
  const { user, addTask, completeTask } = useUserStore();
  const [personalTasks, setPersonalTasks] = useState<Task[]>([]);
  const [activeTask, setActiveTask] = useState<Task | null>(null);
  const [showDetails, setShowDetails] = useState(false);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');

  // 获取任务的useEffect,挂载
  // 修改 useEffect 中的请求部分
  useEffect(() => {
    const fetchTasks = async () => {
      if (!user?.carbonFootprint) {
        setLoading(false);
        return;
      }

      try {
        setLoading(true);
        // 直接通过 URL 参数传递用户信息
        // 修改请求URL
        const response = await axios.get('http://localhost:3001/api/tasks', {
          params: {
            carbonFootprint: user.carbonFootprint
          }
        });

        // 处理响应数据
        console.log('获取任务成功:', response.data);

        setPersonalTasks(response.data.map((task: any) => ({
          ...task,
          id: task._id
        })));
      } catch (err: any) {
        console.error('获取任务失败:', err);
        setError('无法加载任务，请稍后重试');
      } finally {
        setLoading(false);
      }
    };

    fetchTasks();
  }, [user?.carbonFootprint, user?.id]); // 添加 user.id 到依赖数组

  // 完成任务的方法
  const handleCompleteTask = async (taskId: string) => {
    try {
      // 发送完成任务请求到后端
      const response = await axios.post(`http://localhost:3001/api/tasks/${taskId}/complete`, {
        userId: user?.id
      });

      // 更新用户的绿色能量
      if (response.data.greenEnergy !== undefined) {
        setUser({
          ...user!,
          greenEnergy: response.data.greenEnergy
        });
      }
    
      // 更新任务列表中的任务状态
      setPersonalTasks(personalTasks.map(task => 
        task.id === taskId ? {...task, completed: true} : task
      ));
      
      // 关闭任务详情弹窗
      setShowDetails(false);
    } catch (error) {
      console.error('完成任务失败:', error);
      setError('无法完成任务，请稍后重试');
    }
  };

// 查看详情的方法
const handleViewDetails = async (task: Task) => {
  try {
    setLoading(true);
    // 发送请求获取任务详情
    const response = await axios.get(`http://localhost:3001/api/tasks/${task.id}/details`, {
      // params: {
      //   userId: user?.id  // 如果需要的话，也可以携带用户ID
      // }
    });
    console.log('获取任务详情成功:', response.data);
    


// 确保响应数据包含所需字段
if (response.data) {
  const taskDetails = {
    ...response.data,
    id: response.data._id,
    // 确保 criteria 字段存在，如果不存在则使用默认值
    criteria: response.data.criteria || {
      type: 'action',
      target: 1,
      current: 0
    }
  };
  
  setActiveTask(taskDetails);
  setShowDetails(true);
  setError('');
} else {
  throw new Error('任务详情数据无效');
}

} catch (err) {
console.error('获取任务详情失败:', err);
setError('无法获取任务详情，请稍后重试');
// 如果获取详情失败，确保设置的task包含所需字段
setActiveTask({
  ...task,
  criteria: task.criteria || {
    type: 'action',
    target: 1,
    current: 0
  }
});
setShowDetails(true);
} finally {
setLoading(false);
}
};


  // 渲染部分新增加载状态和错误处理
  return (
    <div style={{ padding: '20px', maxWidth: '800px', margin: '0 auto' }}>
      <div style={{ marginBottom: '30px' }}>
        <h2 style={{ color: '#2E8B57', marginBottom: '10px' }}>个性化减碳挑战</h2>
        <p style={{ color: '#666' }}>
          根据您的碳足迹计算结果，我们为您推荐了以下个性化的减碳挑战任务。
          完成这些任务可以帮助您减少碳排放，改善您的星球状态。
        </p>
      </div>

      {/* 任务列表 */}
      <div style={{ display: 'grid', gap: '20px' }}>
        {personalTasks.map(task => (
          <motion.div
            key={task.id}
            whileHover={{ scale: 1.02 }}
            style={{
              backgroundColor: 'white',
              borderRadius: '12px',
              padding: '20px',
              boxShadow: '0 4px 15px rgba(0,0,0,0.1)'
            }}
          >
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '10px' }}>
              <h3 style={{ color: '#2E8B57', margin: 0 }}>{task.title}</h3>
              <div style={{
                padding: '5px 10px',
                borderRadius: '15px',
                backgroundColor: task.completed ? '#E8F5E9' : '#FFF3E0',
                color: task.completed ? '#4CAF50' : '#FF9800'
              }}>
                {task.completed ? '已完成' : '进行中'}
              </div>
            </div>

            <p style={{ color: '#666', marginBottom: '15px' }}>{task.description}</p>

            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
              <div>
                <span style={{ color: '#4CAF50', fontWeight: 'bold' }}>
                  +{task.reward.greenEnergy} 绿色能量
                </span>
                <span style={{ color: '#666', marginLeft: '10px' }}>
                  -{task.reward.carbonReduction} kg CO₂
                </span>
              </div>

              <button
                onClick={() => task.completed ? null : handleViewDetails(task)}
                disabled={task.completed}
                style={{
                  padding: '8px 15px',
                  borderRadius: '8px',
                  border: 'none',
                  backgroundColor: task.completed ? '#E0E0E0' : '#4CAF50',
                  color: 'white',
                  cursor: task.completed ? 'default' : 'pointer'
                }}
              >
                {task.completed ? '已完成' : '查看详情'}
              </button>
            </div>
          </motion.div>
        ))}
      </div>

      {/* 任务详情弹窗 */}
      {showDetails && activeTask && (
        <div style={{
          position: 'fixed',
          top: 0,
          left: 0,
          right: 0,
          bottom: 0,
          backgroundColor: 'rgba(0,0,0,0.5)',
          display: 'flex',
          justifyContent: 'center',
          alignItems: 'center',
          zIndex: 1000
        }}>
          <motion.div
            initial={{ scale: 0.9, opacity: 0 }}
            animate={{ scale: 1, opacity: 1 }}
            style={{
              backgroundColor: 'white',
              borderRadius: '12px',
              padding: '30px',
              maxWidth: '500px',
              width: '90%',
              maxHeight: '90vh',
              overflow: 'auto'
            }}
          >
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '20px' }}>
              <h3 style={{ color: '#2E8B57', margin: 0 }}>{activeTask.title}</h3>
              <button
                onClick={() => setShowDetails(false)}
                style={{
                  border: 'none',
                  background: 'none',
                  fontSize: '24px',
                  cursor: 'pointer',
                  color: '#666'
                }}
              >
                ×
              </button>
            </div>

            <p style={{ color: '#666', marginBottom: '20px' }}>{activeTask.description}</p>

            <div style={{ marginBottom: '20px' }}>
              <h4 style={{ color: '#2E8B57' }}>任务目标</h4>
              <p>完成 {activeTask.criteria.target} {
                activeTask.criteria.type === 'steps' ? '步' :
                  activeTask.criteria.type === 'energy' ? '度' :
                    activeTask.criteria.type === 'action' ? '次' : '参与'
              }</p>
            </div>

            <div style={{ marginBottom: '20px' }}>
              <h4 style={{ color: '#2E8B57' }}>完成奖励</h4>
              <div style={{ display: 'flex', gap: '20px' }}>
                <div>
                  <div style={{ color: '#4CAF50', fontWeight: 'bold' }}>
                    +{activeTask.reward.greenEnergy}
                  </div>
                  <div style={{ color: '#666', fontSize: '14px' }}>绿色能量</div>
                </div>
                <div>
                  <div style={{ color: '#FF9800', fontWeight: 'bold' }}>
                    -{activeTask.reward.carbonReduction} kg
                  </div>
                  <div style={{ color: '#666', fontSize: '14px' }}>CO₂减排</div>
                </div>
              </div>
            </div>

            <button
              onClick={() => handleCompleteTask(activeTask.id)}
              disabled={activeTask.completed}
              style={{
                width: '100%',
                padding: '12px',
                borderRadius: '8px',
                border: 'none',
                backgroundColor: activeTask.completed ? '#E0E0E0' : '#4CAF50',
                color: 'white',
                cursor: activeTask.completed ? 'default' : 'pointer',
                fontSize: '16px'
              }}
            >
              {activeTask.completed ? '已完成' : '标记为已完成'}
            </button>
          </motion.div>
        </div>
      )}
    </div>
  );
};

export default PersonalChallenges;
function setUser(arg0: { greenEnergy: any; id: string; username: string; email: string; carbonFootprint: number; achievements: import("../../types").Achievement[]; planetState: import("../../types").PlanetState; tasks: Task[]; }) {
  throw new Error('Function not implemented.');
}

